<?php
class XA_XHTML_Table extends XA_XHTML {

	public $row_list = array();
	public $label_list = array();
	public $field_list = array();
	public $last_field_position = 0;



	public function __construct($row_list = array()) {
		$this->row_list = $row_list;
	}



	public function addField($field, $label = null) {
		if (is_string($field)) {
			$field = new XA_Table_Field_Simple($field, $label);
		}

		if (!$field->position) {
			$field->position = $this->last_field_position++;
		}

		$this->field_list[$field->name] = $field;
	}



	public function addFieldList($field_list) {
		foreach ($field_list as $field => $label) {
			$this->addField($field, $label);
		}
	}



	public function createDefaultFields() {
		foreach (array_keys(current($this->row_list)) as $field_name) {
			$this->addField($field_name, $field_name);
		}
	}


	public function out() {
		$html_row_list = array();

		if (!$this->field_list) {
			$this->createDefaultFields();
		}

		if (!$this->label_list) {
			foreach ($this->field_list as $field) {
				$this->label_list[$field->name] = $field->label;
			}
		}

		$field_list = array();

		foreach ($this->field_list as $field) {
			$field_list[$field->position] = $field;
		}

		ksort($field_list);

		$toggle = false;

		foreach ($this->row_list as $row) {
			$html_field_list = array();

			foreach ($field_list as $field) {
				$html_field_list[] = $field->out($row);
			}

			$html_row_list[] = '<tr class="'.(isset($row['class']) ? $row['class'] : '').($toggle ? ' toggle' : '').'">'.implode(' ', $html_field_list).'</tr>';
			$toggle = !$toggle;
		}

		return '<table class="'.implode(' ', $this->class_list).'">
				'.($this->label_list ? '<thead><tr><th>'.implode('</th><th>', $this->label_list).'</th><tr></thead>' : '').'
				<tbody>'.implode("\n", $html_row_list).'</tbody>
			</table>';
	}
}
